﻿$(function () {
    function OffLinePaymentVM() {
        var arr = [];
        var timeout = 0;
        var that = this;
        that.offlinePayment = ko.observableArray(window['offlinePayment'] || []);
        that.currentStep = ko.observable(0);//0->1->2[银行入款], 0->11[微信或支付宝等其他]
        that.currentPayType = ko.observable();
        that.amount = ko.observable('').extend({ numeric: 2 });  //输入金额
        that.realName = ko.observable('');
        that.currentTurnType = ko.observable(); //转账类型
        that.belongsBank = ko.observable(''); //所属分行
        that.isSubmiting = ko.observable(false);
        that.choicePre = ko.observable(false); //存款送优惠
        that.autoCountStr = ko.observable('30:00');
        that.offlineAmountSaveConfig = window['offlineAmountSaveConfig'];   //存款优惠判断条件 -- 线下
        that.hasQRCodeImg = ko.computed(function () {
            return that.currentPayType() && that.currentPayType().QRType == 1 && that.currentPayType().QRCodeImg;
        });
        that.hasPreDialog = false;
        that.hasSubmited = ko.observable(false);
        initCopy();
        that.needBelongsBank = ko.computed(function () {
            return that.currentTurnType() && that.currentTurnType() != '网银转账' && that.currentTurnType() != '支付宝转账' && that.currentTurnType() != '手机转账';
        });
        that.currentPayTypeId = ko.computed(function () {
            return that.currentPayType() ? that.currentPayType().ID : 0;
        });
        //默认选中第一个
        //if (that.offlinePayment().length > 0) {
        //    that.currentPayType(that.offlinePayment()[0]);
        //}
        that.reset = function () {
            that.amount('');
            that.realName('');
            that.belongsBank('');
            that.currentTurnType('');
            that.isSubmiting(false);
        }
        //第二步
        that.stepTwo = function () {
            if (that.currentStep() == 0) {
                if (!that.currentPayTypeId()) {
                    utils.tip('请确认并勾选收款账户! ');
                    return;
                }
                var type = that.hasQRCodeImg();
                that.currentStep(type ? 11: 1);
            }
        }
        //第三步
        that.stepThree = function () {
            var amount = that.amount() - 0;
            if (isNaN(amount)) {
                utils.tip('请输入正确的金额');
                return;
            }
            if (!that.amount()) {
                utils.tip('请输入存入金额!');
                return;
            }
            if (!that.realName()) {
                utils.tip('请输入存款人姓名!');
                return;
            }
            if (!that.currentTurnType()) {
                utils.tip('请选择转账类型!');
                return;
            }
            if (that.needBelongsBank() && !that.belongsBank()) {
                utils.tip('请输入所属分行!');
                return;
            }
            var min = that.currentPayType() ? that.currentPayType().MinAmount : 0;
            var max = that.currentPayType() ? that.currentPayType().MaxAmount : 0;
            if (min && amount < min) {
                utils.tip('您输入的金额小于最低存款金额' + min);
                return;
            }
            else if (max && amount > max) {
                utils.tip('您输入的金额大于最高存款金额' + max);
                return;
            }
            that.currentStep(2);  //只有银行入款需要第三步
            autoCount();
        }
        //上一步
        that.stepLast = function () {
            var step = (that.currentStep() - 1) % 10;
            step = Math.max(step, 0);
            that.currentStep(step);
            if (timeout > 0) {
                clearTimeout(timeout);
                timeout = -1;
            }
        }
        //提交
        that.submit = function () {
            var params = that.validation();
            if (!params) return;
            that.isSubmiting(true);
            that.hasSubmited(false);
            var dia = dialog('正在提交中, 请稍候....').showModal();
            $.ajax({
                type: 'POST',
                url: '/CompanyReceipts/UpApply',
                data: params,
                cache: false,
                dataType: 'json',
                success: function (data) {
                    dia.close().remove();
                    if (data.status) {
                        that.hasSubmited(true);
                        if (that.hasQRCodeImg()) {
                            utils.tip('您的订单已提交成功, 请关闭此弹窗, 扫描二维码并转账', true);
                        }
                        else {
                            utils.tip('您的存款申请已成功提交！<br/>财务在收到您的充值后，1分钟内为您确认到账！', true, function () {
                                //var href = window.location.href;
                                //href = href.split(/[?#]/)[0];
                                //href = href.replace(/\/\d{1}$/, '');
                                //window.location.replace(href + '/' + that.currentPayType());
                            });
                        }
                    } else {
                        utils.tip('支付提交失败！' + data.infor);
                    }                       
                }
            });
        }
        //初始化复制按钮
        function initCopy() {
            var needCopyBtns = $('.need-copy');
            if ($('.need-copy').length <= 0) return;
            var lens = needCopyBtns.length;
            if (window['isLTIE9']) {
                for (var i = 0; i < lens; i++) {
                    var btn0 = $(needCopyBtns[i]);
                    btn0.zclip({
                        path: '/Scripts/Util/zclip/ZeroClipboard.swf',
                        copy: btn0.attr('data-clipboard-text'),
                        afterCopy: function () {
                            utils.tip('复制成功！');
                        }
                    });
                }
            }
            else {
                for (var i = 0; i < lens; i++) {
                    var cb = new Clipboard(needCopyBtns[i]);
                    cb.on('success', function (e) {
                        utils.tip('复制成功！');//, 复制内容: ' + e.text);
                        e.clearSelection();
                    });
                }
            }
        }

        //倒计时
        function autoCount() {
            if (!autoCountTotal) return;
            var total = autoCountTotal;
            if (timeout > 0) {
                clearTimeout(timeout);
                timeout = -1;
            }
            function aa() {
                if (total <= 0) {
                    that.autoCountStr('');
                }
                else {
                    var h = Math.floor(total / 3600);
                    var m = total % 3600;
                    var s = m % 60;
                    m = Math.floor(m / 60);
                    var str = '';
                    if (h > 0) {
                        str += h < 10 ? '0' + h : h;
                        str += ':';
                    }
                    str += m < 10 ? '0' + m : m;
                    str += ':';
                    str += s < 10 ? '0' + s : s;
                    that.autoCountStr(str);
                    setTimeout(aa, 1000);
                }
                total--;
            }
            aa();
        }

        that.init();
    }
    //输入验证
    OffLinePaymentVM.prototype.validation = function () {
        var that = this;
        if (!that.currentPayTypeId()) {
            utils.tip('请选择第三方支付! ');
            return;
        }
        var amount = that.amount() - 0;
        if (isNaN(amount)) {
            utils.tip('请输入正确的金额');
            return;
        }
        if (!amount) {
            utils.tip('请输入存入金额!');
            return;
        }
        if (!that.realName()) {
            utils.tip('请输入存款人姓名!');
            return;
        }
        if (that.currentStep() == 3) {
            if (!that.currentTurnType()) {
                utils.tip('请选择转账类型!');
                return;
            }
            if (that.needBelongsBank() && !that.belongsBank()) {
                utils.tip('请输入所属分行!');
                return;
            }
        }
        var min = that.currentPayType() ? that.currentPayType().MinAmount : 0;
        var max = that.currentPayType() ? that.currentPayType().MaxAmount : 0;
        if (min && amount < min) {
            utils.tip('您输入的金额小于最低存款金额' + min);
            return;
        }
        else if (max && amount > max) {
            utils.tip('您输入的金额大于最高存款金额' + max);
            return;
        }
        var params = {
            orderNumber: orderNumber,
            amount: that.amount(),
            userBankId: that.currentPayType().BankId,
            copanyCardId: that.currentPayTypeId(),
            date: (new Date()).format('yyyy/MM/dd hh:mm:ss'),
            way: that.currentTurnType(),
            realName: that.realName(),
            place: that.belongsBank(),
            bankId: that.currentPayTypeId(),
            choicePre: that.choicePre()
        }
        return params;
    }
    OffLinePaymentVM.prototype.init = function () {
        this.SetWithdrawalPwd();
    }
    var rechargeprivilege = Number($('#rechargeprivilege').val());
    var percent = $('#percent').text();
    var isfirst = $('#isfirst').val();
    //存款送优惠
    OffLinePaymentVM.prototype.preference = function (type) {
        var that = this;
        var config = that.offlineAmountSaveConfig;
        var amount = that.amount();
        var line = config.PreferenceLine;
        var needDialog = ((config.RechargePrivilege == 3 && config.IsFirst) || config.RechargePrivilege == 4) && config.PreferencePercent > 0;
        var setTrue = (config.RechargePrivilege == 2 || (config.RechargePrivilege == 1 && config.IsFirst)) && config.PreferencePercent > 0;
        if (config.PreferenceMax > 0 && amount >= line) {
            if (setTrue) {
                that.choicePre(true);
            }
            else if (needDialog && that.hasPreDialog == false) {
                dialog({
                    title: '消息',
                    content: proPreferenceDialogContent(config),
                    width: 300,
                    okValue: type === 1 ? '提交' : '确定',
                    ok: function () {
                        var getPf = $('#GetPreference').is(':checked');
                        that.choicePre(getPf);
                        that.hasPreDialog = true;
                        if (type === 1) {
                            that.submit();
                        }
                    }
                }).showModal();
                return;
            }
        }
        if (type === 1) {
            that.submit();
        }
    }
    //检查是否需要设置资金密码
    OffLinePaymentVM.prototype.SetWithdrawalPwd = function () {
        if ($('#hdWithdrawalpwdIsNull').val() === 'true') {
            dialog({
                title: '取款密码设置',
                content: $('#WithdrawalpwdDialog').html(),
                width: 350,
                okValue: '确定',
                cancelValue: '取消',
                ok: function () {
                    var self = this;
                    var withdrawalpwd = '';
                    $(self.dom.main).find('#withdrawalpwd').find('select').each(function () {
                        withdrawalpwd += $(this).val();
                    });
                    $.post('/Member/SetWithdrawalPwd', { newPwd: withdrawalpwd }, function (json) {
                        alert(json.info);
                        if (json.status) {
                            $('#hdWithdrawalpwdIsNull').val('false');
                        } else {
                            return false;
                        }
                    });
                },
                cancel: function () {
                    this.close();
                }
            }).showModal();
            return;
        }
    }
    var vm = new OffLinePaymentVM();
    if ($("#jsPaymentTips").length > 0) {
        dialog({
            title: '提示',
            content: $('#jsPaymentTips').html(),
            okValue: '确定',
            ok: function () {
                return true;
            }
        }).showModal();
    }
    //生成优惠弹窗所需html文本
    function proPreferenceDialogContent(config) {
        var rtn = '';
        rtn += '<p>';
        rtn += '  尊敬的会员您好：感谢您选择' + window['companySiteName'] + ' ！恭喜您可获得充值送'
        rtn += '  <span>' + config.PreferencePercent + '</span>%(最高: ' + config.PreferenceMax + ')的存款优惠，达到基础流水即可提款!(活动详情请联系在线客服）';
        rtn += '</p>';
        rtn += '<p>';
        rtn += '  <input name="getPreference1" type="radio" id="GetPreference" checked="checked" />';
        rtn += '  <label for="GetPreference">我要获取存款优惠</label>';
        rtn += '</p>';
        rtn += '<p>';
        rtn += '  <input name="getPreference1" type="radio" id="GiveUpPreference" />';
        rtn += '  <label for="GiveUpPreference">我要放弃存款优惠</label>';
        rtn += '</p>';
        return rtn;
    }
    ko.applyBindings(vm, document.getElementById('offlinePaymentContaner'));
});